package org.moonholder.springboot.damocles.config;

import com.alibaba.druid.support.json.JSONUtils;
import org.moonholder.springboot.damocles.entity.vo.ResponseEntity;
import org.moonholder.springboot.damocles.filter.JwtAuthenticationTokenFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.http.HttpMethod;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.session.SessionRegistry;
import org.springframework.security.core.session.SessionRegistryImpl;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Resource
    private UserDetailsService userDetailsService;
    @Resource
    private JwtAuthenticationTokenFilter authenticationTokenFilter;
    @Resource
    private JwtAccessDeniedHandler accessDeniedHandler;
    @Resource
    JwtAuthenticationEntryPoint authenticationEntryPoint;

    @Autowired
    SessionRegistry sessionRegistry;

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests().antMatchers("/admin/*", "/images/*","/verifyCodeImg","/authority/menuData ").permitAll()
                .antMatchers(HttpMethod.OPTIONS, "/**").permitAll().anyRequest().authenticated()
                .and()
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()
                .exceptionHandling().accessDeniedHandler(accessDeniedHandler).authenticationEntryPoint(authenticationEntryPoint)
                .and()
                .addFilterBefore(authenticationTokenFilter, UsernamePasswordAuthenticationFilter.class)
                .csrf().disable().cors();
    }

    @Bean
    PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    /**
     * 处理无权限认证失败逻辑
     */
    @Component
    class JwtAccessDeniedHandler implements AccessDeniedHandler {
        @Override
        public void handle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AccessDeniedException e) throws IOException {
            writeBackExceptionMessage(httpServletResponse, e);
        }
    }

    /**
     * 处理未登录或token失效
     */
    @Component
    class JwtAuthenticationEntryPoint implements AuthenticationEntryPoint {
        @Override
        public void commence(HttpServletRequest requaest, HttpServletResponse response, AuthenticationException e) throws IOException {
            writeBackExceptionMessage(response, e);
        }
    }

    /**
     * 向页面回写异常信息
     *
     * @throws IOException
     */
    private void writeBackExceptionMessage(HttpServletResponse response, Exception e) throws IOException {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json");
        ResponseEntity responseEntity;
        if (e instanceof InsufficientAuthenticationException) {
            response.setStatus(ResponseEntity.Type.UNAUTHORIZED.value());
            responseEntity = ResponseEntity.unauthorized(e.getMessage());
        } else {
            response.setStatus(ResponseEntity.Type.FORBIDDEN.value());
            responseEntity = ResponseEntity.forbidden(e.getMessage());
        }
        PrintWriter writer = response.getWriter();
        writer.println(JSONUtils.toJSONString(responseEntity));
        writer.flush();
    }

    /**
     * 注册bean sessionRegistry
     */
    @Bean
    public SessionRegistry sessionRegistry() {
        return new SessionRegistryImpl();
    }
}
